<template>
  <el-dialog
    :visible.sync="isVisible"
    title="设置路径巡航点"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="onClose"
  >
    <div class="dialog-container">
      <el-form
        ref="pathForm"
        :model="path"
        :rules="pathRules"
        label-width="100px"
      >
        <!-- 预置点选择 -->
        <el-form-item label="预置点:">
          <el-select
            v-model="selectedPreset"
            placeholder="请选择预置点"
            @change="handleChange"
          >
            <el-option
              v-for="preset in presetOptions"
              :key="preset.id"
              :label="preset.name"
              :value="preset.id"
            ></el-option>
          </el-select>
          <el-button class="add-button" @click="addPreset"
            >添加预置点</el-button
          >
        </el-form-item>

        <!-- 显示已选择的预置点 -->
        <el-form-item label="已选预置点:">
          <draggable class="drag-wrapper" v-model="path.presets">
            <div
              v-for="(preset, index) in path.presets"
              :key="preset.id"
              class="preset-item"
            >
              {{ preset.name }} (顺序: {{ index + 1 }})
              <!-- 移除图标 -->
              <i class="el-icon-close" @click="removePreset(index)"></i>
              <!-- <el-button @click="removePreset(index)">移除</el-button> -->
            </div>
          </draggable>
        </el-form-item>
        <!-- 巡航间隔 -->
        <el-form-item label="巡航间隔:" prop="interval">
          <el-input-number
            v-model="path.interval"
            :min="1"
            :max="100"
            :step="1"
            :precision="0"
            placeholder="请输入巡航间隔"
          ></el-input-number>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSave">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addPath, getPathById, getPresetList } from '@/api/camera'; // 确保导入正确的接口
import draggable from 'vuedraggable';
export default {
  name: 'AddPathDialog',
  components: {
    draggable,
  },
  data() {
    return {
      isVisible: false,
      path: {
        id: '',
        presets: [], // 存储多个预置点
        interval: '',
      },
      selectedPreset: '',
      presetOptions: [],
      pathRules: {
        // name: [
        //   {
        //     required: true,
        //     message: '请输入名称',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
      },
    };
  },
  computed: {
    // 当前播放的视频对象
    currentVideo() {
      return this.$store.getters['playVideo/getCurrentPlayingVideo'];
    },
    // config配置
    config() {
      return this.$store.getters['websocketClient/config'];
    },
    // 预置点id
    preset_ids() {
      return this.path.presets.map((preset) => preset.id);
    },
  },
  methods: {
    handleChange(value) {
      this.selectedPreset = value;
    },
    /**
     * 显示添加对话框
     */
    async show() {
      this.isVisible = true;
      await this.getPresetName();
      await this.getPathInfo();
    },
    /**
     * 隐藏对话框
     */
    onClose() {
      this.isVisible = false;
      // 清除表单数据
      this.path = {
        id: '',
        presets: [],
        interval: '',
      };
      // 清除表单校验
      this.$refs.pathForm.resetFields();
    },
    /**
     * 取消
     */
    onCancel() {
      this.isVisible = false;
      // 清除表单数据
      this.path = {
        id: '',
        presets: [],
        interval: '',
      };
      // 清除表单校验
      this.$refs.pathForm.resetFields();
    },
    /**
     * 保存
     */
    onSave() {
      console.log(this.path.presets);
      console.log(this.preset_ids);
      this.$refs.pathForm.validate(async (valid) => {
        if (!valid) {
          return false;
        } else {
          const param = {
            id: this.path.id,
            camera_id: this.currentVideo.id,
            preset_ids: this.preset_ids,
            interval: this.path.interval,
          };
          const res = await addPath(param);
          if (res.code === 200) {
            this.$message.success('添加成功');
            this.isVisible = false;
            // // 添加成功并发送指令
            // this.$store.dispatch('websocketClient/sendMessage', {
            //   ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
            //   message: {
            //     cameraId: this.currentVideo.cameraId,
            //     command: this.config['btnCommand']['pathSet'],
            //     data: {
            //       name: this.path.name,
            //     },
            //   },
            // });
          } else {
            this.$message.error('添加失败');
          }
          this.isVisible = false;
        }
      });
    },
    /**
     * 获取预置点名称数据
     */
    async getPresetName() {
      try {
        const param = {
          camera_id: this.currentVideo.id,
        };
        const res = await getPresetList(param);
        if (res.code === 200) {
          this.presetOptions = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 获取路径巡航数据
     */
    async getPathInfo() {
      try {
        const param = {
          camera_id: this.currentVideo.id,
        };
        const res = await getPathById(param);
        if (res.code === 200 && res.data) {
          this.path.id = res.data.id;
          this.path.interval = res.data.interval;
          // 根据 preset_ids 的顺序从 presetOptions 中查找预置点
          console.log(this.presetOptions);
          this.path.presets = [...res.data.presets];
          console.log(this.path);
        }
      } catch (error) {
        console.log(error);
      }
    },
    addPreset() {
      if (this.selectedPreset) {
        const selected = this.presetOptions.find(
          (p) => p.id === this.selectedPreset
        );
        if (selected) {
          this.path.presets.push(selected);
          this.selectedPreset = '';
        }
      }
    },
    removePreset(index) {
      this.path.presets.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-container {
  padding: 20px;
}
:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-select {
  width: 66%;
}

.drag-wrapper {
  width: 90%;
}

.el-input-number {
  width: 90%;
}
// .add-button {
//   width: 16%;
// }

.preset-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px;
  border: 1px solid #ebeef5;
  margin-bottom: 8px;
  cursor: move;
  i {
    cursor: pointer;
    border: 1px solid #ebeef5;
    padding: 4px;
    border-radius: 50%;
    &:hover {
      background-color: #7399f3;
    }
  }
}
</style>
